<template>
  <div class="admin-form">
    <el-form :model="formData" ref="form" label-width="120px">
      <el-form-item
        label="库管理员姓名："
        prop="name"
        :rules="[{ required: true, message: '请输入库管理员姓名', trigger: 'blur' }]"
      >
        <el-input v-model="formData.name" placeholder="请输入库管理员姓名"></el-input>
      </el-form-item>

      <el-form-item
        label="登录手机号："
        prop="mobile"
        :rules="[{ required: true, message: '请输入登录手机号', trigger: 'blur' }]"
      >
        <el-input v-model="formData.mobile" placeholder="请输入登录手机号"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, defineProps,onMounted  } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { addAdmin } from "@/api/set/keeper.js"; 
import { editAdmin } from "@/api/set/keeper.js"; 

//路由引入使用用于组件之间的跳转
const router = useRouter();
const route = useRoute();

const formData = ref({
  id: 0,
  name: "",
  mobile: ""
});


//存储编辑行数据
const edit = (row) => {
  localStorage.setItem('editRow', JSON.stringify(row));
  router.push({
    path: '/set/keeper/form',
    query: { type: 'edit', id: row.id }
  });
};


// 判断是新增还是编辑
const type = route.query.type;
const id = route.query.id;

// 编辑时填充数据
onMounted(() => {
  if (type === 'edit') {
    const row = JSON.parse(localStorage.getItem('editRow'));
    if (row && row.id == id) {
      formData.value = { ...row };
    }
  }
});



// 提交表单
const submitForm = async () => {
  if (!formData.value.name || !formData.value.mobile) {
    ElMessage.error("请输入完整的信息");
    return;
  }

  let res;
  if (type === 'add') {
    res = await addAdmin(formData.value);
    if (res.code === 200) {
      ElMessage.success("新增管理员成功");
      router.push("/set/keeper");
    } else {
      ElMessage.error("新增管理员失败");
    }
  } else {
    res = await editAdmin(formData.value);
    if (res.code === 200) {
      ElMessage.success("编辑管理员成功");
      router.push("/set/keeper");
    } else {
      ElMessage.error("编辑管理员失败");
    }
  }
};

// 取消操作
const cancel = () => {
  router.push("/set/keeper");
};
</script>

<style scoped>
.admin-form {
  margin: 20px;
  max-width: 500px;
}
</style>
